package minit

import (
	"errors"
	"gitee.com/dennis-mxx/mxx-core-v2/mdb"
	"gitee.com/dennis-mxx/mxx-core-v2/menv"
	"gitee.com/dennis-mxx/mxx-core-v2/mlogger"
	"gitee.com/dennis-mxx/mxx-core-v2/mmeta"
	"gitee.com/dennis-mxx/mxx-core-v2/mredis"
	"gitee.com/dennis-mxx/mxx-core-v2/mreflect"
	"gitee.com/dennis-mxx/mxx-core-v2/mweb"
	"os"
	"reflect"
)

func InitializeFile(defEnv string) {
	Initialize(&menv.FileRender{}, defEnv)
}

func Initialize(loader menv.ConfigRender, defEnv string, dest ...any) {
	var config string
	if loader.GetPath() != "" {
		config = loader.GetPath()
	} else {
		config = "./conf/config-$env.toml"
	}
	mmeta.SetSys("logger.level", "info")
	mmeta.SetSys("logger.dir", "./logger/")
	mmeta.SetSys("env", defEnv)
	mmeta.SetSys("config", config)
	mmeta.AppendArgs("env", defEnv, "Program running environment")
	mmeta.AppendArgs("config", config, "Program config path")
	fields := mreflect.LoadStructTag("", "toml", reflect.TypeOf(menv.Environment).Elem())
	for i := range fields {
		mmeta.AppendArgs(fields[i], "", "System Program : "+fields[i])
	}

	mmeta.ParseArgs()

	loader.SetEnv(mmeta.Get("env").(string))
	loader.SetConfigPath(mmeta.Get("config").(string))
	readerFile := loader.Render()

	if err := mmeta.Unmarshal(menv.Environment); err != nil {
		panic(errors.Join(err, errors.New("load config exception")))
	}
	for i := range dest {
		if err := mmeta.Unmarshal(dest[i]); err != nil {
			panic(errors.Join(err, errors.New("load dest exception")))
		}
	}

	mlogger.InitZap()
	mlogger.Out.Info("env [", mmeta.Get("env"), "]")
	mlogger.Out.Info("render config file [" + readerFile + "] successful !")

	if menv.Environment.Mysql != nil && menv.Environment.Mysql.Addr != "" {
		mdb.InitMysql(menv.Environment.Mysql)
	}

	if menv.Environment.Redis != nil && menv.Environment.Redis.Addr != "" {
		mredis.InitRedis(menv.Environment.Redis)
	}
	if menv.Environment.Gin != nil && menv.Environment.Gin.Port != 0 {
		mweb.InitWeb(menv.Environment.Gin)
		if menv.Environment.Gin.Pprof {
			mweb.InitProf(mweb.Engine)
		}
	}

	mlogger.Out.Info("<<< Environment load complete . ServerName : [", menv.Environment.ServerName, "] PID : ", os.Getpid(), " >>>")
	mlogger.Out.Info("<<< mxx-core: https://gitee.com/dennis-mxx/mxx-core-v2/tags >>>")

}
